import 'dart:convert';
import 'dart:io';
import 'package:base_flutter/base_flutter.dart';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ls_work/a_yyt/models/policy_warning_entity.dart';
import 'package:ls_work/a_yyt/models/upload_entity.dart';
import 'package:ls_work/a_yyt/widget/yyt_voice_widget.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/locale_photo_browser.dart';
import 'package:flutter/cupertino.dart';

import '../../util/flat_button.dart';



class PolicyDealPage extends StatefulWidget {
  final PolicyWarningInfo? info;
  final VoidCallback? callBack;
  PolicyDealPage({Key? key, this.info, this.callBack});
  @override
  _PolicyDealPageState createState() => _PolicyDealPageState();
}

class _PolicyDealPageState extends State<PolicyDealPage> {
  TextEditingController textFieldEditer = TextEditingController();
  List<File> imageList = [];
  List<Upload> imagePathList = [];
  Upload? _recordfileModel;
  // String _voicePath = '';
  // double _audioTimeLength = 0.0;
  OverlayEntry? overlayEntry;

  @override
  void initState() {
    super.initState();
  }

  ///开始语音录制的方法
  startRecord() {
    print("开始录制");
  }

  stopRecord(String? path, num? audioTimeLength) {
    print("结束束录制");
    print("音频文件位置" + (path??""));
    print("音频录制时长" + audioTimeLength.toString());
    if (!TextUtil.isEmpty(path)) {
      _upLoadImage(path!, type: 1);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('报警处理'),
        elevation: 0.5,
        centerTitle: true,
        actions: [
          FlatsButton(
            onPressed: _send,
            child: Text(
              '提交',
              style: TextStyle(
                fontSize: 16,
                color: Colours.app_main,
              ),
            ),
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(15),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text(
                  '${widget.info?.customerName ?? ''}',
                  style: TextStyles.textDark18,
                ),
                Gaps.hGap10,
                Expanded(
                  child: Text(
                    '${widget.info?.floorNo}${widget.info?.roomNo??""}',
                    style: TextStyles.textGray14,
                  ),
                ),
              ],
            ),
            if(!(widget.info?.position??"").isNullOrEmpty()) ...[
              Gaps.vGap12,Text('报警位置：${widget.info?.position??""}',style: TextStyles.textDark16,)],
            Gaps.vGap12,
            Icon(
              Icons.directions_walk,
              color: Colors.orange[200],
            ),
            Gaps.vGap12,
            Text(
              '首次呼叫： ${DateUtil.formatDateStr(widget.info?.createdDate??"", format: 'MM-dd HH:mm:ss')}',
              style: TextStyles.textGray18,
            ),
            Gaps.vGap12,
            Text.rich(TextSpan(children: [
              TextSpan(
                text: '本次报警',
                style: TextStyles.textGray18,
              ),
              TextSpan(
                text: '3',
                style: TextStyle(fontSize: 18, color: Colors.red),
              ),
              TextSpan(
                text: '次呼叫',
                style: TextStyles.textGray18,
              ),
            ])),
            Gaps.vGap12,
            Text(
              '最后呼叫： ${DateUtil.formatDateStr(widget.info?.lastCallTime??"", format: 'MM-dd HH:mm:ss')}',
              style: TextStyles.textGray18,
            ),
            Gaps.vGap10,
            Gaps.vGap10,
            Gaps.line,
            Container(
              padding: EdgeInsets.only(top: 20, bottom: 20),
              alignment: Alignment.topLeft,
              height: 200,
              color: Colors.white,
              child: TextField(
                controller: textFieldEditer,
                maxLines: 10,
                maxLength: 300,
                autofocus: false,
                decoration: InputDecoration(
                  hintText: "填写处理说明",
                  hintMaxLines: 20,
                  fillColor: Colours.bg_color,
                  filled: true,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                    borderSide: BorderSide.none,
                  ),
                ),
              ),
            ),
            Gaps.line,
            Padding(
              padding: EdgeInsets.fromLTRB(10, 20, 10, 10),
              child: Text(
                '提示：长按图片可删除图片，最多选择9张图片',
                style: TextStyles.textGray12,
              ),
            ),
            Container(
              width: ScreenUtil.getScreenW(context),
              height: (ScreenUtil.getScreenW(context) - 60) /
                      4 *
                      (((imageList.length + 1) / 4).ceil()) +
                  10 * (((imageList.length + 1) / 4).ceil()),
              color: Colors.white,
              child: GridView.builder(
                physics: NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4, //每行三列
                  childAspectRatio: 1.0, //显示区域宽高相等
                  crossAxisSpacing: 10,
                  mainAxisSpacing: 10,
                ),
                itemCount: imageList.length + 1,
                itemBuilder: (context, index) {
                  if (index == imageList.length) {
                    return FlatsButton(
                      onPressed: _pickImageFromSource,
                      child: Icon(
                        Icons.camera_enhance,
                        color: Colors.orange,
                        size: 40,
                      ),
                      color: Colours.bg_color,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(5.0),
                      ),
                    );
                  } else {
                    return InkWell(
                      onTap: () {
                        AppNavigator.push(
                          context,
                          PhotoBrowser(
                            imageLocaleList: imageList,
                            currentPageValue: index,
                          ),
                        );
                      },
                      onLongPress: () {
                        _showCupertinoAlertDialog(context, index);
                      },
                      child: ClipRRect(
                        borderRadius: BorderRadius.all(Radius.circular(5)),
                        child: Image.file(
                          imageList[index],
                          fit: BoxFit.cover,
                        ),
                      ),
                    );
                  }
                },
              ),
            ),
            Gaps.line,
            Gaps.vGap15,
            Gaps.vGap15,
            // YYTVoiceWidget(
            //   startRecord: startRecord,
            //   stopRecord: stopRecord,
            // ),
          ],
        ),
      ),
    );
  }

  ///提交处理
  _send() async {
    var map = {
      "callInfoId": widget.info?.id,
      "content": textFieldEditer.text,
    };
    List tempList = [];
    if (imagePathList.length > 0) {
      for (var item in imagePathList) {
        tempList.add({
          'id': item.id,
          'path': item.path,
          'callId': widget.info?.id,
          'docKind': 0,
        });
      }
    }
    //docKind  0图片 1录音 2视频
    if (_recordfileModel != null) {
      tempList.add({
        'id': _recordfileModel?.id,
        'path': _recordfileModel?.path,
        'callId': widget.info?.id,
        'docKind': 1,
      });
    }
    if (tempList.length > 0) {
      map['attachList'] = tempList;
    }
    HttpUtil.instance
        .getDio()
        .post(HttpApi.policyWarningDeal, data: map)
        .then((r) {
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map['msg']);
          if(widget.callBack!=null){
            widget.callBack!();
          }
          Navigator.of(context).pop();
        }
      } else {
        Toast.show(map['msg'] as String);
      }
    }).catchError((e) {
      print(e.toString());
    });
  }

  ///选择图片方式
  _pickImageFromSource() {
    if (imageList.length == 9) {
      Toast.show('最多上传9张');
      return;
    }
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return new Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            new ListTile(
              leading: new Icon(Icons.photo_camera),
              title: new Text("相机"),
              onTap: () async {
                var imageFile =
                    await ImagePicker().pickImage(source: ImageSource.camera);
                if (imageFile == null) return;
                setState(() {
                  imageList.add(File(imageFile.path));
                  _upLoadImage(imageFile.path);
                });
                Navigator.pop(context);
              },
            ),
            new ListTile(
              leading: new Icon(Icons.photo_library),
              title: new Text("相册"),
              onTap: () async {
                var imageFile =
                    await ImagePicker().pickImage(source: ImageSource.gallery);
                if (imageFile == null) return;
                setState(() {
                  imageList.add(File(imageFile.path));
                  _upLoadImage(imageFile.path);
                });
                print(imageFile);
                Navigator.pop(context);
              },
            ),
          ],
        );
      },
    );
  }

  void _showCupertinoAlertDialog(BuildContext cxt, int index) {
    showCupertinoDialog<int>(
      context: cxt,
      builder: (cxt) {
        return CupertinoAlertDialog(
          title: Text('提示'),
          content: Text('是否要删除？'),
          actions: <Widget>[
            CupertinoDialogAction(
              child: Text("确定"),
              onPressed: () {
                setState(() {
                  imageList.removeAt(index);
                  if (imageList.length == imagePathList.length - 1) {
                    imagePathList.removeAt(index);
                  }
                });
                Navigator.pop(context);
              },
            ),
            CupertinoDialogAction(
              child: Text("取消"),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          ],
        );
      },
    );
  }

  showView(BuildContext context) {
    if (overlayEntry == null) {
      overlayEntry = new OverlayEntry(builder: (content) {
        return Positioned(
          top: MediaQuery.of(context).size.height * 0.5 - 80,
          left: MediaQuery.of(context).size.width * 0.5 - 80,
          child: Material(
            child: Center(
              child: Opacity(
                opacity: 0.8,
                child: Container(
                  width: 100,
                  height: 100,
                  decoration: BoxDecoration(
                    color: Color(0xff77797A),
                    borderRadius: BorderRadius.all(Radius.circular(20.0)),
                  ),
                  child: Column(
                    children: <Widget>[
                      Container(
                        child: Text(
                          'pppppp',
                          style: TextStyle(
                            fontStyle: FontStyle.normal,
                            color: Colors.white,
                            fontSize: 14,
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      });
      Overlay.of(context).insert(overlayEntry!);
    }
  }

  ///上传
  _upLoadImage(String filePath, {int type = 0}) async {
    print(filePath);

    ///0 - 图片 1 - 语音
    var name =
        filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length);
    FormData formData = new FormData.fromMap({
      'fileType': filePath.substring(filePath.lastIndexOf('.') + 1),
      'fileToUpload': await MultipartFile.fromFile(filePath, filename: name),
    });
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post(HttpApi.upload, data: formData).then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());

        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            Upload model = Upload.fromJson(map['data']);
            setState(() {
              if (type == 0) {
                imagePathList.add(model);
              } else {
                _recordfileModel = model;
              }
            });
          } else {
            Toast.show(map["msg"]);
          }
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
